package com.jinzhi.jzapi.examination.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.domain.LogDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.service.LogService;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.examination.pojo.ExaminationsVo;
import com.jinzhi.jzapi.examination.pojo.TestPaperVo;
import com.jinzhi.jzapi.utils.MD5Util;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/jzApi/examinations")
public class ApiExaminationsController extends BaseController {

    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private DictService dictService;
    @Autowired
    private StuSignUpComService stuSignUpService;

    @Autowired
    private StuSignUpService stuSignUpComService;

    @Autowired
    private ExaminationBatchComService examinationBatchService;

  //  @Autowired
  //  private ExaminationBatchService examinationBatchService1;

    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;
    @Autowired
    private ExaminationAnswerSheetService examinationAnswerSheetService;
    @Autowired
    private ExaminationAnswerSheetComService examinationAnswerSheetComService;
    @Autowired
    private LogService logService;
    @Autowired
    private ExceptionAddtimeService exceptionAddtimeService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private TemplateDetailsService templateDetailsService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private ItemBankService itemBankService;
    @Autowired
    private UserService userService;
    @Autowired
    private ExaminationResultsComService examinationResultsComService;
    /**
     *  验证手机号是否存在 如果存在则进行绑定
     *
     * @Param: []
     * @Author: xzy
     * @Date: 2020-03-25
     */
    @GetMapping("/userPapers")
    @Log("小程序获取考试批次接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> userPapers(String phone,String ticketNumber,String name,String idNumber) {

        Long userId= userService.userPhone(phone);
            if(userId==null||userId==0){
                return ApiResult.fail("手机号在系统中不存在！");
            }
        StuSignUpComDO stuSignUpDO = stuSignUpService.findOneByKv("name", name, "ticket_number", ticketNumber,"id_number",idNumber);
        if (stuSignUpDO == null) {
            return ApiResult.fail("信息错误！");
        }
        stuSignUpDO.setUserId(userId);
        stuSignUpService.updateById(stuSignUpDO);

        return ApiResult.success();
    }
    /**
     * 小程序考试批次接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/appletsSelExamination")
    @Log("小程序获取考试批次接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> appletsSelExamination() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsTeachers();

        if(examinationsVos != null && examinationsVos.size() > 0) {
            for(int i=0;i<examinationsVos.size();i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                examinationsVos.get(i).setExamNotes(examNotes);

                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);

                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }

    /**
     * 小程序考试批次接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/appletsSelExaminationScreen")
    @Log("小程序获取所有筛选考试批次接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> appletsSelExaminationScreen() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsScreen();

        if(examinationsVos != null && examinationsVos.size() > 0) {
            for(int i=0;i<examinationsVos.size();i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                examinationsVos.get(i).setExamNotes(examNotes);

                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);

                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }

    /**
     * 新增考试程序端-考试信息接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/getBatch")
    @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> getBatch(Long id) {
     ExaminationBatchComDO examinationBatchDO=   examinationBatchService.selectById(id);
        ExaminationsVo examinationsVos=new ExaminationsVo();
        if(examinationBatchDO != null ) {

                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                long duration = examinationBatchDO.getEndTime().getTime()-examinationBatchDO.getStartTime().getTime();
              examinationsVos.setExamNotes(examNotes);
              examinationsVos.setDuration((duration/60000)+"");
                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
               examinationsVos.setBackGroundImage(backGroundImage);
            examinationsVos.setId(examinationBatchDO.getId());
            examinationsVos.setStartTime(examinationBatchDO.getStartTime());
            examinationsVos.setEndTime(examinationBatchDO.getEndTime());
                //EhCacheUtil.put("selExamination", examinationsVo);
            examinationsVos.setName(examinationBatchDO.getName());

            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }

    /**
     * 考试程序端-考试信息接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: xzy
     * @Date: 2020-03-25
     */
    @GetMapping("/selExaminationComAll3")
    @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExaminationComAll3() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selExaminationComAll3();

        if(examinationsVos != null && examinationsVos.size() > 0) {
            for(int i=0;i<examinationsVos.size();i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                long duration = examinationsVos.get(i).getEndTime().getTime()-examinationsVos.get(i).getStartTime().getTime();
                examinationsVos.get(i).setExamNotes(examNotes);
                examinationsVos.get(i).setDuration((duration/60000)+"");
                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);
                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }


    /**
     * 考试程序端-考试信息接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: xzy
     * @Date: 2020-03-25
     */
    @GetMapping("/selExaminationCom")
    @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExaminationCom() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        Map hashMap = new HashMap();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsComNow(hashMap);

        if(examinationsVos != null && examinationsVos.size() > 0) {
            for(int i=0;i<examinationsVos.size();i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                long duration = examinationsVos.get(i).getEndTime().getTime()-examinationsVos.get(i).getStartTime().getTime();
                examinationsVos.get(i).setExamNotes(examNotes);
                examinationsVos.get(i).setDuration((duration/60000)+"");
                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);
                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }


    @GetMapping("/selExaminationComType")
    @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExaminationCom(int competitionType) {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        Map hashMap = new HashMap();
        hashMap.put("type",competitionType);
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsComNow(hashMap);

        if(examinationsVos != null && examinationsVos.size() > 0) {
            for(int i=0;i<examinationsVos.size();i++) {
                Map<String, String> map = new HashMap<>();
                map.put("name", "考试须知");
                map.put("type", "exa_exam_notes");
                String examNotes = dictService.selDicBy(map);
                long duration = examinationsVos.get(i).getEndTime().getTime()-examinationsVos.get(i).getStartTime().getTime();
                examinationsVos.get(i).setExamNotes(examNotes);
                examinationsVos.get(i).setDuration((duration/60000)+"");
                map.clear();
                map.put("name", "考试提交成功页广告语");
                map.put("type", "exam_bg");
                String backGroundImage = dictService.selDicBy(map);
                examinationsVos.get(i).setBackGroundImage(backGroundImage);
                //EhCacheUtil.put("selExamination", examinationsVo);
            }
            return ApiResult.success(examinationsVos);
        }else {
            return ApiResult.fail("暂无考试信息！");
        }
    }


    /**
     * 考试程序端-考试信息接口
     *  查看所有竞赛接口
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: xzy
     * @Date: 2023-05-10
     *
     * 缺少批次人数统计数据  2023-5-18已加
     *
     */
    @GetMapping("/selExaminationComAll")
    @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExaminationComAll() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsComNowAll();
//
//        if(examinationsVos != null && examinationsVos.size() > 0) {
//            for(int i=0;i<examinationsVos.size();i++) {
//                Map<String, String> map = new HashMap<>();
//                map.put("name", "考试须知");
//                map.put("type", "exa_exam_notes");
//                String examNotes = dictService.selDicBy(map);
//                long duration = examinationsVos.get(i).getEndTime().getTime()-examinationsVos.get(i).getStartTime().getTime();
//                examinationsVos.get(i).setExamNotes(examNotes);
//                examinationsVos.get(i).setDuration((duration/60000)+"");
//                map.clear();
//                map.put("name", "考试提交成功页广告语");
//                map.put("type", "exam_bg");
//                String backGroundImage = dictService.selDicBy(map);
//                examinationsVos.get(i).setBackGroundImage(backGroundImage);
//                //EhCacheUtil.put("selExamination", examinationsVo);
//            }
            return ApiResult.success(examinationsVos);
    }


    /**
     * 考试程序端-考试信息接口
     *
     * @Description: 获取考试信息，包括考试名称、开考时间、结束时间、时长、考试须知，考试题型等介绍
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-25
     */
    @GetMapping("/selExamination")
    @Log("考试程序端-考试信息接口")
    @ApiOperation(value = "考试程序端-考试信息接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExamination() {
        //ExaminationsVo examinationsVo = examinationBatchService.selExaminations();
        List<ExaminationsVo> examinationsVos = examinationBatchService.selListExaminationsNow();
       // List<ExaminationsVo> examinationsVosceshi = examinationBatchService.selListExaminationsNowCeshi();
        //正式考试加上测试考试
       // examinationsVos.addAll(examinationsVosceshi);

        if(examinationsVos != null && examinationsVos.size() > 0) {
        	for(int i=0;i<examinationsVos.size();i++) {
        		Map<String, String> map = new HashMap<>();
        		map.put("name", "考试须知");
        		map.put("type", "exa_exam_notes");
        		String examNotes = dictService.selDicBy(map);
        		long duration = examinationsVos.get(i).getEndTime().getTime()-examinationsVos.get(i).getStartTime().getTime();
        		examinationsVos.get(i).setExamNotes(examNotes);
                examinationsVos.get(i).setDuration((duration/60000)+"");
        		map.clear();
        		map.put("name", "考试提交成功页广告语");
        		map.put("type", "exam_bg");
        		String backGroundImage = dictService.selDicBy(map);
        		examinationsVos.get(i).setBackGroundImage(backGroundImage);
        		//EhCacheUtil.put("selExamination", examinationsVo);
        	}
          return ApiResult.success(examinationsVos);
        }else {
        	return ApiResult.fail("暂无考试信息！");
        }
//        if (examinationsVo != null) {
//            Map<String, String> map = new HashMap<>();
//            map.put("name", "考试须知");
//            map.put("type", "exa_exam_notes");
//            String examNotes = dictService.selDicBy(map);
//            examinationsVo.setExamNotes(examNotes);
//
//            map.clear();
//            map.put("name", "考试提交成功页广告语");
//            map.put("type", "exam_bg");
//            String backGroundImage = dictService.selDicBy(map);
//            examinationsVo.setBackGroundImage(backGroundImage);
//
//            EhCacheUtil.put("selExamination", examinationsVo);
//            return ApiResult.success(examinationsVo);
//        } else {
//            return ApiResult.fail("暂无考试信息！");
//        }
    }

    //将考生状态改为考试中
    @PostMapping("/serversBanners")
    @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试轮播图接口返回", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> serversBanners() {
       Map map=new HashMap();
       map.put("Type","serversBanners");
        List<DictDO>  list=   dictService.selectListBy(map);

       return ApiResult.success(list);

    }

    //将考生状态改为考试中
    @PostMapping("/changeState")
    @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public boolean changeState(String id) {
    	StuSignUpComDO stuSignUpDO = stuSignUpService.selectById(id);
    	stuSignUpDO.setState(8);
    	return stuSignUpService.updateById(stuSignUpDO);
    }


    //判断考试是否开始
    @PostMapping("/changeBatchState")
    @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result<?> changeBatchState(String id) {
        //判断考试是否开始
        ExaminationBatchComDO examinationBatchComDO = examinationBatchService.selectById(id);
        if(examinationBatchComDO==null){
            return Result.fail("暂无考试！");
        }
        else if(examinationBatchComDO!=null && examinationBatchComDO.getType()!=null && examinationBatchComDO.getState()!=4){
            return Result.fail("考试未开始！");
        }
        //判断是否抽取试卷
        List<ExaminationPaperDO> examinationPaperDOS = examinationPaperService.selectList(new EntityWrapper<ExaminationPaperDO>().eq("ebatch_id", id).eq("state", 99));
        if(examinationPaperDOS==null || examinationPaperDOS.isEmpty()){
            return Result.fail("未抽取试卷！");
        }
        return Result.ok();
    }
    
    //获取服务器系统时间
    @PostMapping("/getNowDateTime")
    @Log("考试程序端-获取服务器时间")
    @ApiOperation(value = "考试程序端-获取服务器时间", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Date getNowDateTime() {
    	return new Date();
    }
    
    /**
     * 考试程序端-考试登录接口
     *   考试登录
     * @Description: 考试程序端考生登录获取考生信息，参数：考生姓名、身份证号、考号、考试批次id
     * @Param: [name, idCard, ticketNumber, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/loginExamination")
    @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> loginExamination(String num2,String randomCipher,Integer competitionType) {

        if (StringUtils.isBlank(num2)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(randomCipher)) {
            return ApiResult.lack("");//缺少参数
        }
//        if (StringUtils.isBlank(id)) {
//            return ApiResult.fail("暂无考试！");
//        }
        long startTime=System.currentTimeMillis();
       // StuSignUpDO stuSignUpDO = stuSignUpService.findOneByKv("name", name, "ticket_number", ticketNumber,"id_number",idNumber,"cbatch_id",id);
        StuSignUpComDO stuSignUpDO = stuSignUpService.findOneByKv( "num2",num2,"random_cipher",randomCipher,"competition_type",competitionType);

        long endTime=System.currentTimeMillis();
        System.out.println(endTime-startTime);
        if (stuSignUpDO == null) {
            return ApiResult.fail("信息错误！");
        } else {


            EntityWrapper wrapper =new EntityWrapper();
            wrapper.eq("stu_sign_id",stuSignUpDO.getId());
            ExaminationAnswerSheetComDO examinationAnswerSheetComDO = examinationAnswerSheetComService.selectOne(wrapper);
            if (examinationAnswerSheetComDO !=null){
                return ApiResult.fail("已经提交答卷，不能再次进入考试！");
            }

        	//String idNumber=stuSignUpDO.getIdNumber();
        	//String pw = ticketNumber.substring(ticketNumber.length()-4)+idNumber.substring(idNumber.length()-4);
        	//if(!pw.equals(password)) {
        	//	return ApiResult.fail("密码错误！");
        	//}
            ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(stuSignUpDO.getCbatchId());
            if (examinationBatchDO == null) {
                return ApiResult.fail("暂无考试2！");
            } else {
                if (examinationBatchDO.getId().equals(stuSignUpDO.getCbatchId())) {
                        //stuSignUpDO.setState(8);
                        boolean bbc = stuSignUpService.updateById(stuSignUpDO);
                        if (bbc) {
                            Map map = new HashMap();
                            map.put("stuSignId", stuSignUpDO.getId());//考生id
                            map.put("roomNumber", stuSignUpDO.getEallocationNum());//考场号
                            map.put("name", stuSignUpDO.getName());//考生姓名
                            map.put("ticketNumber", stuSignUpDO.getTicketNumber());//考号
                            map.put("idCard", stuSignUpDO.getIdNumber());//身份证号码
                            map.put("photo", stuSignUpDO.getPhoto());//考生照片
                            map.put("seatNumber", stuSignUpDO.getTicketNumber().substring(stuSignUpDO.getTicketNumber().length() - 2));//座位号
                            map.put("state", stuSignUpDO.getState());//考生状态
                            map.put("nowDate", new Date());
                            map.put("num2", stuSignUpDO.getNum2());//二次加密
                            Map<String, String> map1 = new HashMap<>();
                    		map1.put("name", "允许考试切屏次数");
                    		map1.put("type", "exam_allow_num");
                            map.put("allowNum", dictService.selDicBy(map1));
                            //添加认证码，认证码格式是： md5（"考号"+"YYMMDD"）
                            Date currentTime = new Date();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                            String dateString = formatter.format(currentTime);
                            String cookieCode = MD5Util.md5(stuSignUpDO.getTicketNumber(), dateString);
                            map.put("cookieCode", cookieCode);
                            DictDO dic = dictService.findOneByKv("type" , "exam_num");
                            DictDO dic1 = dictService.findOneByKv("type" , "send_num");
                            map.put("batchName",examinationBatchDO.getName());
                            map.put("time" , dic.getValue());

                            map.put("cbatchId" , examinationBatchDO.getId());
                            map.put("dates" , dic1.getValue());
                            return ApiResult.success(map);
                        } else {
                            return ApiResult.fail("系统错误，请重试！");
                        }
                } else {
                    return ApiResult.fail("暂无考试3！");
                }
            }
        }
    }







    /**
     * 考试程序端-考试登录接口
     *   考试登录
     * @Description: 考试程序端考生登录获取考生信息，参数：考生姓名、身份证号、考号、考试批次id
     * @Param: [name, idCard, ticketNumber, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/loginExaminations")
    @Log("考试程序端-考试登录接口")
    @ApiOperation(value = "考试程序端-考试登录接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> loginExaminations(String num2,String randomCipher) {
        if (StringUtils.isBlank(num2)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(randomCipher)) {
            return ApiResult.lack("");//缺少参数
        }
//        if (StringUtils.isBlank(id)) {
//            return ApiResult.fail("暂无考试！");
//        }
        long startTime=System.currentTimeMillis();
        // StuSignUpDO stuSignUpDO = stuSignUpService.findOneByKv("name", name, "ticket_number", ticketNumber,"id_number",idNumber,"cbatch_id",id);
        StuSignUpComDO stuSignUpDO = stuSignUpService.findOneByKv( "num2",num2,"random_cipher",randomCipher);

        long endTime=System.currentTimeMillis();
        System.out.println(endTime-startTime);
        if (stuSignUpDO == null) {
            return ApiResult.fail("信息错误！");
        } else {
            //String idNumber=stuSignUpDO.getIdNumber();
            //String pw = ticketNumber.substring(ticketNumber.length()-4)+idNumber.substring(idNumber.length()-4);
            //if(!pw.equals(password)) {
            //	return ApiResult.fail("密码错误！");
            //}
            ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(stuSignUpDO.getCbatchId());
            if (examinationBatchDO == null) {
                return ApiResult.fail("暂无考试2！");
            } else {
                if (examinationBatchDO.getId().equals(stuSignUpDO.getCbatchId())) {
                        //stuSignUpDO.setState(8);
                        boolean bbc = stuSignUpService.updateById(stuSignUpDO);
                        if (bbc) {
                            Map map = new HashMap();
                            map.put("stuSignId", stuSignUpDO.getId());//考生id
                            map.put("roomNumber", stuSignUpDO.getEallocationNum());//考场号
                            map.put("name", stuSignUpDO.getName());//考生姓名
                            map.put("ticketNumber", stuSignUpDO.getTicketNumber());//考号
                            map.put("idCard", stuSignUpDO.getIdNumber());//身份证号码
                            map.put("photo", stuSignUpDO.getPhoto());//考生照片
                            map.put("seatNumber", stuSignUpDO.getTicketNumber().substring(stuSignUpDO.getTicketNumber().length() - 2));//座位号
                            map.put("state", stuSignUpDO.getState());//考生状态
                            map.put("nowDate", new Date());
                            map.put("num2", stuSignUpDO.getNum2());//二次加密
                            Map<String, String> map1 = new HashMap<>();
                            map1.put("name", "允许考试切屏次数");
                            map1.put("type", "exam_allow_num");
                            map.put("allowNum", dictService.selDicBy(map1));
                            //添加认证码，认证码格式是： md5（"考号"+"YYMMDD"）
                            Date currentTime = new Date();
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                            String dateString = formatter.format(currentTime);
                            String cookieCode = MD5Util.md5(stuSignUpDO.getTicketNumber(), dateString);
                            map.put("cookieCode", cookieCode);
                            DictDO dic = dictService.findOneByKv("type" , "exam_num");
                            DictDO dic1 = dictService.findOneByKv("type" , "send_num");

                            map.put("time" , dic.getValue());

                            map.put("cbatchId" , examinationBatchDO.getId());
                            map.put("dates" , dic1.getValue());
                            return ApiResult.success(map);
                        } else {
                            return ApiResult.fail("系统错误，请重试！");
                        }
                } else {
                    return ApiResult.fail("暂无考试3！");
                }
            }
        }
    }






    /**
     * 考试程序端-考试试卷接口
     *
     * @Description: 查询试卷数据，包括试卷id、试卷编号、试卷名称、题目、选项、题号;
     * 参数：考试批次id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selTeacherExaminationPaper")
    @Log("考试程序端-考试试卷接口")
    @ApiOperation(value = "考试程序端-考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selTeacherExaminationPaper(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无试卷！");
        }
        Map map = (Map) EhCacheUtil.get("examinationPaperDO" + id);
        if (map == null) {
            Map mapre = new HashMap();
            ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", Long.parseLong(id), "state", 1);
            if (examinationPaperDO != null) {
                mapre.put("id", examinationPaperDO.getId());//试卷id
                mapre.put("name", examinationPaperDO.getName());//试卷名称
                mapre.put("numbers", examinationPaperDO.getNumbers());//试卷编号

                Map map1 = new HashMap();
                map1.put("epaperId", examinationPaperDO.getId());
                List<ExaminationQuestionsDO> ExaminationQuestionsDOs = examinationQuestionsService.findByKv("epaper_id", examinationPaperDO.getId());
                mapre.put("questions", ExaminationQuestionsDOs);//试卷试题

                EhCacheUtil.put("examinationPaperDO" + id, mapre);
                return ApiResult.success(mapre);
            } else {
                return ApiResult.fail("暂无试卷！");
            }
        } else {
            return ApiResult.success(map);
        }
    }



    /**
     * 考试程序端-考试试卷接口
     *
     * @Description: 查询试卷数据，包括试卷id、试卷编号、试卷名称、题目、选项、题号;
     * 参数：考试批次id
     * @Param: [id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selExaminationPaper")
    @Log("考试程序端-考试试卷接口")
    @ApiOperation(value = "考试程序端-考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selExaminationPaper(String id) {
        if (StringUtils.isBlank(id)) {
            return ApiResult.fail("暂无试卷！");
        }

        Map map = (Map) EhCacheUtil.get("examinationPaperDO" + id);
        if (map == null) {
            Map mapre = new HashMap();
            ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", Long.parseLong(id), "state", 99);
            if (examinationPaperDO != null) {
                mapre.put("id", examinationPaperDO.getId());//试卷id
                mapre.put("name", examinationPaperDO.getName());//试卷名称
                mapre.put("numbers", examinationPaperDO.getNumbers());//试卷编号

                Map map1 = new HashMap();
                map1.put("epaperId", examinationPaperDO.getId());
                List<TestPaperVo> testPaperVos = examinationQuestionsService.selTestPaper(map1);
                mapre.put("questions", testPaperVos);//试卷试题

              //  EhCacheUtil.put("examinationPaperDO" + id, mapre);
                return ApiResult.success(mapre);
            } else {
                return ApiResult.fail("暂无试卷！");
            }
       } else {
            return ApiResult.success(map);
       }
    }
    
    /**
     * 考试程序端-考模拟考试试卷接口
     *
     * @Description: 获得模拟考试试卷数据，包括试卷id、试卷编号、试卷名称、限时、题目、选项、题号
     * 参数：考试批次id
     * @Param: [profile_id]  证书概况id
     * @Param: [grade]  证书等级 （0高级，1中级，2初级）
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selTrainExaminationPaper")
    @Log("考试程序端-考模拟考试试卷接口")
    @ApiOperation(value = "考试程序端-考模拟考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selTrainExaminationPaper(String profile_id,String  grade) {
        if (StringUtils.isBlank(profile_id)) {
            profile_id = "1241245212023312386L"; //当前默认为  幼儿照护职业技能等级证书
         }
        if (StringUtils.isBlank(grade)) {
            return ApiResult.fail("等级错误！");
        }else{
            if(!(grade.equals("0")||grade.equals("1")||grade.equals("2")))
                return ApiResult.fail("等级错误！");
        }
        String cn_id = "";
        Date nowDate = new Date();
        String key = nowDate.getDay()+""+nowDate.getHours()+""+nowDate.getMinutes()/10;
        //减少sql查询负担
        if(profile_id.equals("1241245212023312386")){//幼儿照护
            key+="幼儿照护"+grade;
            Map ehcacheMap = (Map)EhCacheUtil.get(key);
            if(ehcacheMap!=null){
                return ApiResult.success(ehcacheMap);
            }
            else{
                EhCacheUtil.remove((String)EhCacheUtil.get("LastTime幼儿照护"));
                EhCacheUtil.put("LastTime幼儿照护",key);
            }
            switch (grade){
                case "0":
                    cn_id = "1241246900989841410";break;
                case "1":cn_id = "1241246701718458370";break;
                case "2":cn_id = "1241245991509544961";break;
            }
        }else if(profile_id.equals("1375327865662226434")){//产后恢复
            key+="产后恢复"+grade;
            Map ehcacheMap = (Map)EhCacheUtil.get(key);
            if(ehcacheMap!=null){
                return ApiResult.success(ehcacheMap);
            }
            else{
                EhCacheUtil.remove((String)EhCacheUtil.get("LastTime产后恢复"));
                EhCacheUtil.put("LastTime产后恢复",key);
            }
            switch (grade){
                case "0":cn_id = "1399199728653402113";break;
                case "1":cn_id = "1399199555814522882";break;
                case "2":cn_id = "1399199123935428609";break;
            }
        }else{
            ApiResult.fail("证书编号错误！");
        }

        Map mapre = new HashMap(); //返回值
        mapre.put("id", "000000");//试卷id
        mapre.put("name","");//试卷名称
        mapre.put("numbers", "");//试卷编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        Date endTime = new Date(now.getTime() + 60*60*1000);//毫秒，共60分钟
        mapre.put("endTime",sdf.format(endTime));//结束时间
        ArrayList<Map> retQuestions = new ArrayList<>();
                    TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.findOneByKv("type", 0, "news_id", cn_id);
                    if (testPaperTemplateDO == null) {
                        return  ApiResult.fail("未找到对应的试卷模板，请检查或重试！");
                    } else {
                        List<TemplateDetailsDO> templateDetailsDOs = templateDetailsService.findByKv("tptemplate_id", testPaperTemplateDO.getId());
                        if (templateDetailsDOs != null && templateDetailsDOs.size() > 0) {
                            int th = 1;
                            //从题库中查询并将信息添加至试卷试题
                            for (TemplateDetailsDO templateDetailsDO : templateDetailsDOs) {
                                //暂时去除实操题的生成
                                if (templateDetailsDO.getType() < 3) {
                                        Map<Object, Object> map = new HashMap<>();
                                        map.put("kpointsId", templateDetailsDO.getKpointsId());//templateDetailsDO.getKpointsId()); 当前默认为空，不做限制
                                        map.put("profileId", profile_id);//certificationBatchDO.getProfileId());
                                        map.put("topicTypes", templateDetailsDO.getType());
                                        map.put("item_bank_type", "0"); //只用练习题  0：练习题;1：考试题;不加这条则取所有题库
                                        int titleNumber = 0;
                                        if (grade.equals("0")) { //certificateNewsDO.getGrade() == 0
                                            map.put("grade", "高级");
                                        } else if (grade.equals("1")) {//certificateNewsDO.getGrade() == 1
                                            map.put("grade", "中级");
                                        } else if (grade.equals("2")) {//certificateNewsDO.getGrade() == 2
                                            map.put("grade", "初级");
                                        }
                                        TemplateDetailsDO t = templateDetailsService.findOneByKv("kpoints_id",templateDetailsDO.getKpointsId(),"tptemplate_id",templateDetailsDO.getTptemplateId(),"type",templateDetailsDO.getType()+3);
                                        if(t!=null){
                                            titleNumber=templateDetailsDO.getTitleNumber()+t.getTitleNumber();
                                        }else{
                                            titleNumber=templateDetailsDO.getTitleNumber();
                                        }
                                        map.put("titleNumber",titleNumber );
                                        List<Map<Object, Object>> maps = itemBankService.selRandList(map);//目前已经是根据单个知识点直接查询，已经调整了like查询了
                                        if (maps != null &&  maps.size() == titleNumber) {
                                            for (int i = 0; i < maps.size(); i++) {
                                                Map testPaperMap = new HashMap();//试题明细
                                                testPaperMap.put("id",retQuestions.size()+1);//examinationPaperDO1.getId()
                                                testPaperMap.put("topicTypes",maps.get(i).get("topicTypes"));
                                                testPaperMap.put("introduce",maps.get(i).get("topicContent").toString());
                                                testPaperMap.put("options",maps.get(i).get("options").toString());
                                                testPaperMap.put("answer",maps.get(i).get("rightKey").toString());
                                                testPaperMap.put("score",templateDetailsDO.getScore());
                                                testPaperMap.put("topicAnalysis",maps.get(i).get("topicAnalysis"));
                                                testPaperMap.put("resourceType",maps.get(i).get("resourceType"));
                                                testPaperMap.put("titleNumber",th);
                                                th+=1;
                                                retQuestions.add(testPaperMap);//添加试卷试题
                                            }
                                        } else {
                                            String errorMsg="题库数量不足，无法生成考试！（"+templateDetailsDO.getKpointsId()+"）";
                                            return  ApiResult.fail(errorMsg);
                                        }
                                }
                            }
                        } else {

                            return  ApiResult.fail("试卷模板详情信息有误或没有信息，生成试卷失败，请检查并稍后重试！");
                        }
                        mapre.put("questions", retQuestions);//添加试卷试题
                    }
        EhCacheUtil.put(key, mapre);
        return ApiResult.success(mapre);
    }

    /**
     * 考试程序端-考模拟考试试卷接口
     *
     * @Description: 获得模拟考试试卷数据，包括试卷id、试卷编号、试卷名称、限时、题目、选项、题号
     * 参数：考试批次id
     * @Param: [profile_id]  证书概况id
     * @Param: [grade]  证书等级 （0高级，1中级，2初级）
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-26
     */
    @PostMapping("/selYuyinExaminationPaper")
    @Log("小程序端-育婴员模拟考试试卷接口")
    @ApiOperation(value = "小程序端-育婴员模拟考试试卷接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selYuyinExaminationPaper() {
        String profile_id = "1379704595300278274"; //育婴员

        Map m = new HashMap<String,String>();
        m.put("name", "育婴员题库练习");
        m.put("type", "yuyin_brushTopic_on-off");
        String examNotes = dictService.selDicBy(m);
        if(!examNotes.equals("on")){
            return  ApiResult.fail("无法访问");
        }

        Map mapre = new HashMap(); //返回值
        mapre.put("id", "000000");//试卷id
        mapre.put("name","");//试卷名称
        mapre.put("numbers", "");//试卷编号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        Date endTime = new Date(now .getTime() + 90*60*1000);//毫秒，共90分钟
        mapre.put("endTime",sdf.format(endTime));//结束时间
        ArrayList<Map> retQuestions = new ArrayList<>();


        List<ItemBankDO> maps = itemBankService.findByKv("profile_id", profile_id,"item_bank_type", "0");//目前已经是根据单个知识点直接查询，已经调整了like查询了
        if (maps != null && maps.size() > 0) {
            for (int i = 0; i < maps.size(); i++) {
                //ExaminationQuestionsDO examinationQuestionsDO = new ExaminationQuestionsDO();
                Map testPaperMap = new HashMap();//试题明细

                testPaperMap.put("id",i+1);//examinationPaperDO1.getId()
                testPaperMap.put("topicTypes",maps.get(i).getTopicTypes());
                testPaperMap.put("introduce",maps.get(i).getTopicContent());
                testPaperMap.put("options",maps.get(i).getOptions());
                testPaperMap.put("answer",maps.get(i).getRightKey());
                testPaperMap.put("score",1);
                testPaperMap.put("topicAnalysis",maps.get(i).getTopicAnalysis());

                testPaperMap.put("resourceType",maps.get(i).getResourceType());
                testPaperMap.put("titleNumber",i+1);//题号
                retQuestions.add(testPaperMap);//添加试卷试题
            }
        } else {
            return  ApiResult.fail("题库中暂未题目，请检查并稍后重试！");
        }
        mapre.put("questions", retQuestions);//添加试卷试题

        return ApiResult.success(mapre);


    }


    /**
     * 考试程序端-考试答卷提交接口
     *
     * @Description: 考生提交考卷；参数：考生id，试卷id，答卷集合
     * @Param: [stuSignId, epaperId, answerList]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-27
     */
    @PostMapping("/selAnswerSheet")
    @Log("考试程序端-考试答卷提交接口")
    @ApiOperation(value = "考试程序端-考试答卷提交接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> selAnswerSheet(String stuSignId, String epaperId, String answerList, String code) {
        if (StringUtils.isBlank(stuSignId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(epaperId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(answerList)||answerList=="") {
            return ApiResult.fail("提交异常，请联系平台管理员！");//缺少参数
        }
//        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//        if (request != null) {
//            String userIp = IPUtils.getIpAddr(request);
//            if(userIp.equals("127.0.0.1")){
//                return ApiResult.fail("提交失败，请重试！");
//            }
//        }
        StuSignUpComDO stuSignUpDO = stuSignUpService.selectById(Long.parseLong(stuSignId));
        if(stuSignUpDO.getName().contains("jzwy")){
            return ApiResult.success("提交成功");
        }
        if (stuSignUpDO != null) {
            //添加认证码，认证码格式是： md5（"考号"+"YYMMDD"）
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(currentTime);
            boolean bb = MD5Util.verify(stuSignUpDO.getTicketNumber(), dateString, code);
            if (bb) {
                ExaminationAnswerSheetComDO examinationAnswerSheetDO = examinationAnswerSheetComService.findOneByKv("epaper_id", epaperId, "stu_sign_id", stuSignId);
                if (examinationAnswerSheetDO != null) {
                    return ApiResult.fail("试卷已提交，如有问题请联系监考员");
                } else {
                    //提交试卷新增绑定考试批次字段
                    ExaminationAnswerSheetComDO examinationAnswerSheetDO1 = new ExaminationAnswerSheetComDO();
                    examinationAnswerSheetDO1.setEpaperId(Long.parseLong(epaperId));//试卷id
                    examinationAnswerSheetDO1.setStuSignId(Long.parseLong(stuSignId));//考生id
                    examinationAnswerSheetDO1.setAnswerList(answerList);//答卷集合
                    examinationAnswerSheetDO1.setExamType(2);
//                    Wrapper<StuSignUpDO> wrapper = new EntityWrapper<StuSignUpDO>();
//                    wrapper.eq("cbatch_id",Long.parseLong(stuSignId));
//                  List<StuSignUpDO> list=  stuSignUpService.selectList(wrapper);
//                    if(list.size()>0){
//                        //新增考试批次ID绑定
//                        examinationAnswerSheetDO1.setBatchId();
//                    }else {
//
//                    }
                    boolean b = examinationAnswerSheetComService.insert(examinationAnswerSheetDO1);
                    if (b) {
                        stuSignUpDO.setState(10);
                        boolean bbc = stuSignUpService.updateById(stuSignUpDO);
                        if (bbc) {
                            return ApiResult.success("提交成功");
                        } else {
                            return ApiResult.fail("提交失败，请重试");
                        }
                    } else {
                        return ApiResult.fail("提交失败，请重试！");
                    }
                }
            } else {
                saveLog("考试程序端-考试答卷提交接口", stuSignId + ";" + epaperId + ";" + answerList, stuSignUpDO.getUserId(), stuSignUpDO.getName());
                return ApiResult.fail("信息错误，请重试");
            }
        } else {
            saveLog("考试程序端-考试答卷提交接口", stuSignId + ";" + epaperId + ";" + answerList, -2L, "不明来历者");
            return ApiResult.fail("信息错误，请重试");
        }
    }

    private void saveLog(String valuess, String params, Long id, String name) {
        LogDO sysLog = new LogDO();
        sysLog.setOperation(valuess + "，访问异常，请注意！");
        sysLog.setParams(params);
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (request != null) {
            sysLog.setMethod(request.getMethod() + " " + request.getRequestURI());
            // 设置IP地址
            sysLog.setIp(IPUtils.getIpAddr(request));
        }
        // 用户名
        sysLog.setUserId(id);
        sysLog.setUsername(name);
        sysLog.setTime(11);
        sysLog.setGmtCreate(new Date());
        // 保存系统日志
        logService.insert(sysLog);
    }


    @PostMapping("/uploadpptById")
    @Log("实操上传ppt")
    @ApiOperation(value = "实操上传ppt", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result<?> uploadpptById(Long stuSignId, String pptfile) {

        StuSignUpComDO stuSignUpDO = stuSignUpService.selectById(stuSignId);
        if (stuSignUpDO == null) {
            saveLog("考试程序端-考试答卷提交接口", stuSignId + ";" + pptfile + ";" , -2L, "不明来历者");
            return Result.fail("信息错误，请重试");
        }
        ExaminationAnswerSheetComDO examinationAnswerSheetComDO = new ExaminationAnswerSheetComDO();
        examinationAnswerSheetComDO.setPptfile(pptfile);
        examinationAnswerSheetComDO.setStuSignId(stuSignId);
        Boolean aBoolean = examinationAnswerSheetComService.insert(examinationAnswerSheetComDO);
        return aBoolean ? Result.ok() : Result.fail();
    }


}
